package com.bub.pay.outer.redis;


import cn.jpush.api.JPushClient;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;
import com.bub.pay.framework.common.template.JPushVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author wing
 */
public class AsyncJPushService implements Runnable {

	/**
	 * Logger
	 */
	private static final Logger log = LoggerFactory.getLogger(AsyncJPushService.class);

	private final JPushClient jPushClient;
	private final JPushVo jPushVo;

	public AsyncJPushService(final JPushClient jPushClient, final JPushVo jPushVo) {
		this.jPushClient = jPushClient;
		this.jPushVo = jPushVo;
	}

	private boolean isEmptyParam() {
		return null == jPushVo || null == jPushClient;
	}

	@Override
	public void run() {
		if (isEmptyParam()) {
			log.error("AsyncJPushService parameter must not be null");
			return;
		}

		try {
			//指定当前推送的android通知
			AndroidNotification androidNotification = AndroidNotification.newBuilder()
					.setAlert(jPushVo.getContent())
					.setTitle(jPushVo.getTitle())
					//此字段为透传字段，不会显示在通知栏。用户可以通过此字段来做一些定制需求，如特定的key传要指定跳转的页面（value）
					.addExtras(jPushVo.getMessageData()).build();
			//指定当前推送的iOS通知
			IosNotification iosNotification = IosNotification.newBuilder()
					.setAlert(jPushVo.getContent())
					.setBadge(+1)
					.setSound("happy")  //这里是设置提示音
					.addExtras(jPushVo.getMessageData()).build();

			//将两个平台整合
			Notification notification = Notification.newBuilder()
					.addPlatformNotification(androidNotification)
					.addPlatformNotification(iosNotification)
					.build();

			//推送的关键,构造一个payload
			PushPayload payload = PushPayload.newBuilder()
					.setPlatform(Platform.all())
					.setAudience(Audience.registrationId(jPushVo.getRegistrationId()))
					.setNotification(notification)
					//设置发送环境
					.setOptions(Options.newBuilder().setApnsProduction(jPushVo.isProd()).build())
					//此部分内容不会展示到通知栏上
					.setMessage(Message.content(""))    //自定义信息
					.build();
			jPushClient.sendPush(payload);
		} catch (Exception ex) {
			log.error("AsyncJPushService send email error:", ex);
		}

	}

}
